package com.iris.live.services.services.impl;

import com.iris.live.services.common.reconsitution.FinanceConstant;
import com.iris.live.services.data.models.数据字典表Model;
import com.iris.live.services.data.models.销售财务表Model;
import com.iris.live.services.data.models.销售财务账目表Model;
import com.iris.live.services.data.repositories.FinanceReturnTicketRepository;
import com.iris.live.services.data.repositories.数据字典Repository;
import com.iris.live.services.data.repositories.销售财务表Repository;
import com.iris.live.services.data.repositories.销售财务账目表Repository;
import com.iris.live.services.models.RequestBase;
import com.iris.live.services.models.ResultData;
import com.iris.live.services.report.ExcelReportContext;
import com.iris.live.services.report.IExcelReportService;
import com.iris.live.services.report.sources.ExportReturnTicketListSource;
import com.iris.live.services.services.FinanceReceivablesService;
import com.iris.live.services.services.FinanceReturnTicketService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.OutputStream;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.Map;

/**
 * 财务系统对接模块(退票模块)--业务层
 */
@Service
@Transactional
public class FinanceReturnTicketServiceImpl implements FinanceReturnTicketService{

    private static final Logger logger = LoggerFactory.getLogger(FinanceReturnTicketServiceImpl.class);

    @Resource
    private FinanceReturnTicketRepository financeReturnTicketRepository;

    @Resource
    private 销售财务账目表Repository 销售财务账目Repository;

    @Resource
    private FinanceReceivablesService financeReceivablesService;

    @Resource
    private 销售财务表Repository 销售财务表Repository;

    @Resource
    private IExcelReportService excelReportService;

    @Resource(name = "ExportReturnTicketListSource")
    private ExportReturnTicketListSource exportReturnTicketListSource;

    @Resource
    private 数据字典Repository 数据字典Repository;

    @Override
    @Transactional(readOnly = true)
    public ResultData getReturnTicketForPage(ReturnTicketPageRequest request) {
        ResultData result = new ResultData();
        result.setPageData(financeReturnTicketRepository.getReturnTicketForPage(request));
        return result;
    }

    @Override
    public ResultData refundTicket(ReturnTicketRequest params) throws Exception {
        ResultData result = new ResultData();
        Timestamp time = new Timestamp(System.currentTimeMillis());
        Date date = new Date(System.currentTimeMillis());
        // 得到待红冲的票据信息
        销售财务账目表Model detailModel = 销售财务账目Repository.findOne(params.financeDetailNumber);
        if (null == detailModel) {
            result.setMessage("缺少相关财务账目明细数据，操作失败！");
            result.setResult("false");
            return result;
        }
        销售财务表Model financeModel = 销售财务表Repository.findOne(detailModel.get财务编号());
        if (null == financeModel) {
            result.setMessage("缺少相关财务数据，操作失败！");
            result.setResult("false");
            return result;
        }

        if (null != detailModel.get是否红冲() && "1".equals(detailModel.get是否红冲())) {
            result.setMessage("发票已经红冲过，不可再次红冲！");
            result.setResult("false");
            return result;
        }

        // 发票登记完毕的状态下，不可以退整车票
        数据字典表Model dictinaryModel = 数据字典Repository.get数据字典By名称(detailModel.get发票项目());
        if ("item_allCar".equalsIgnoreCase(dictinaryModel.get字典值()) && FinanceConstant.INVOICE_COMPLETE.equals(financeModel.get开票状态())) {
            result.setMessage("发票登记完毕，不能退整车票！");
            result.setResult("false");
            return result;
        }

        // 创建红冲账目记录
        销售财务账目表Model detailModel2 = new 销售财务账目表Model();
        detailModel2.set财务编号(detailModel.get财务编号());
        detailModel2.set关联编号(detailModel.get账目编号());
        detailModel2.set订单编号(detailModel.get订单编号());
        detailModel2.set账目类型(FinanceConstant.HCFP);
        detailModel2.set账目单号(financeReceivablesService.generateOperationNumber(FinanceConstant.HF));
        detailModel2.set账目日期(new Date(System.currentTimeMillis()));  // 取当天日期
        detailModel2.set账目金额(detailModel.get账目金额().negate());
        detailModel2.set交易凭证号(detailModel.get交易凭证号());
        detailModel2.set发票项目(detailModel.get发票项目());
        detailModel2.set发票类型(detailModel.get发票类型());
        detailModel2.set发票抬头(detailModel.get发票抬头());
        detailModel2.set纳税人识别号(detailModel.get纳税人识别号());
        detailModel2.set客户地址(detailModel.get客户地址());
        detailModel2.set客户电话(detailModel.get客户电话());
        detailModel2.set客户开户行(detailModel.get客户开户行());
        detailModel2.set客户账号(detailModel.get客户账号());
        detailModel2.set是否红冲("0");
        detailModel2.set创建用户(params.user);
        detailModel2.set创建时间(time);
        detailModel2.set修改用户(params.user);
        detailModel2.set修改时间(time);
        detailModel2.set删除状态("0");
        detailModel2.set操作日期(time);
        销售财务账目Repository.save(detailModel2);

        // 更新发票账目记录
        detailModel.set关联编号(detailModel2.get账目编号());
        detailModel.set是否红冲("1");
        detailModel.set修改时间(time);
        detailModel.set修改用户(params.user);
        detailModel.set操作日期(time);
        销售财务账目Repository.save(detailModel);

        // 更新销售财务表的退票金额
        financeModel.set退票金额(financeModel.get退票金额().add(detailModel.get账目金额().negate()));
        return result;
    }

    @Override
    public void exportReturnTicketList(String permit, Map map, RequestBase request, OutputStream outputStream) {
        try {
            ExcelReportContext context = new ExcelReportContext();
            String[] columns = map.get("columns").toString().split("[|]");
            map.remove("columns");
            context.setTemplate("templates/财务退票导出模板.xlsx")
                    .setFileName("财务退票导出模板.xlsx")
                    .setSource(exportReturnTicketListSource)
                    .setStaticSheet(false)
                    .setStartCellIndex(0)
                    .setEndCellIndex(columns.length)
                    .setAutoRowExtended(true)
                    .addParam("permit", permit)
                    .addParam("param", map)
                    .addParam("columns", columns)
                    .addParam("request", request);

            excelReportService.export(context, outputStream);
        } catch (Exception e) {
            logger.error("导出退票列表数据异常", e);
        }
    }
}
